/*
 * Copyright 2013 Walter Lütgenau.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package offset.nodes.client.dialog.navigation.model;

import java.net.URL;
import javax.swing.JApplet;
import netscape.javascript.JSObject;
import offset.nodes.client.model.component.AppletEnvironment;
import offset.nodes.client.model.component.AppletInfo;
import offset.nodes.client.view.BaseApplet;

/**
 * Add showDocument to inherited environment.
 * 
 * @author Walter Lütgenau
 */
public class DialogAppletEnvironment extends AppletEnvironment implements DialogAppletContext {
    JApplet base;
    JSObject callingNode; // the node, whose javascript method created the applet, provided the node is passed to the applet.
    JSObject event; // the event, that was passed to the javascript method creating the applet or null

    public DialogAppletEnvironment(JApplet base, AppletInfo info, JSObject callingNode, JSObject event) throws Exception {
        super(info);
        this.base = base;
        this.callingNode = callingNode;
        this.event = event;
    }

    /** Request to overlay the current page with a new one */
    public void showDocument(URL url) {
        JSNode window = new JSNode((JSObject) JSObject.getWindow(base));
        JSNode contentFrame = window.getNode("parent.contentFrame");
        contentFrame.getObject().setMember("location", url.toString());        
    }    
    
    /** as above but with a Frame target */
    public void showDocument(URL url, String frame) {
        if (BaseApplet.SHOW_SAME_WINDOW.equals(frame)) {
            showDocument(url);
            return;
        }
            
        base.getAppletContext().showDocument(url, frame);
    }
    
    /*** DialogAppletContext **************/
    
    public DialogAppletContext getDialogAppletContext() {
        return this;
    }

    @Override
    public JSNode getCallingNode() {
        if (callingNode == null)
            return null;
        
        return new JSNode(callingNode);
    }

    @Override
    public JSEvent getEvent() {
        if (event == null)
            return null;
        
        return new JSEvent(event);
    }

    @Override
    public JSWindow getWindow() {
        return new JSWindow(JSObject.getWindow(base));
    }
}
